﻿using Cysharp.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;

/// <summary>
/// 配置文件管理器
/// </summary>
public class ConfigLoader : GameFrameClassBase
{
    private static Dictionary<string, object> s_Configs = new Dictionary<string, object>();

    public override async UniTask InitAsync()
    {
        var configTypes = Tools.GetAllTypesWithAttribute<ConfiguableAttribute>();
        foreach (var type in configTypes)
        {
            object config = await LoadConfig(type);
            if (config == null) continue;
            s_Configs[type.Name] = config;
        }
    }

    /// <summary>
    /// 加载配置表
    /// </summary>
    private static async UniTask<object> LoadConfig(Type type)
    {
        string configKey = type.Name;
        TextAsset asset = await Addressables.LoadAssetAsync<TextAsset>($"Configs/{configKey}.json");
        if (asset == null)
        {
            Debug.LogError($"ConfigLoader 配置加载失败：{configKey}文件不存在");
            return null;
        }
        Debug.Log($"ConfigLoader 配置加载成功：{configKey}");
        return asset.text.ToObject(typeof(List<>).MakeGenericType(type));
    }

    /// <summary>
    /// 根据配置数据类型获取配置数据列表
    /// </summary>
    public static List<T> GetConfig<T>()
    {
        var configuableAttr = typeof(T).GetCustomAttribute<ConfiguableAttribute>();
        if (configuableAttr == null)
        {
            Debug.LogError($"ConfigLoader 配置读取失败：{typeof(T).Name}不是配置");
            return null;
        }
        string configKey = typeof(T).Name;
        if (!s_Configs.TryGetValue(configKey, out object config))
        {
            Debug.LogError($"ConfigLoader 配置读取失败：{configKey}不存在");
            return null;
        }
        return config as List<T>;
    }
}